"""
created@2019/11/3
"""
from flask_restful import Resource, reqparse
from sqlalchemy import desc, or_
from models.silo import Message
from utils.resp import Resp

MSG_TYPE = ['text', 'news']


class MessageListApi(Resource):

    def get(self):
        "获取消息列表信息"

        parser = reqparse.RequestParser()
        parser.add_argument('wx_app_id', type=int)
        args = parser.parse_args()
        wx_app_id = args.get('wx_app_id', '')

        if wx_app_id or wx_app_id==0:
            # 如果通过公众号消息返回所有文本消息和该公众号下的媒体消息
            messages = Message.query.filter(
                or_(Message.wx_app_id==wx_app_id,
                    Message.wx_app_id==0),
                Message.deleted_at.is_(None)).order_by(desc(Message.id)).all()
        else:
            # 返回所有消息
            messages = Message.query.filter(Message.deleted_at.is_(None)).order_by(desc(Message.id)).all()
            """
            SELECT silo.messages.id AS silo_messages_id, silo.messages.created_at AS silo_messages_created_at, silo.messages.updated_at AS silo_messages_updated_at, silo.messages.title AS silo_messages_title, silo.messages.wx_app_id AS silo_messages_wx_app_id, silo.messages.deleted_at AS silo_messages_deleted_at, silo.messages.msg_type AS silo_messages_msg_type, silo.messages.content AS silo_messages_content, silo.messages.media_id AS silo_messages_media_id 
            FROM silo.messages 
            WHERE silo.messages.deleted_at IS NULL ORDER BY silo.messages.id DESC
            """
        data = [
            {
                'title': message.title,
                'msg_id': message.id,
                'wx_app_id': message.wx_app_id,
                'content': message.content,
                'media_id': message.media_id,
                'msg_type': message.msg_type,
                'update_at': str(message.updated_at),
                'created_at': str(message.created_at)
            } for message in messages
        ]
        return Resp.ok(data=data)

    def post(self):
        """创建公众号消息"""

        parser = reqparse.RequestParser()
        parser.add_argument('title', type=str, required=True)
        parser.add_argument('msg_type', type=str, required=True)
        parser.add_argument('wx_app_id', type=int, required=True)
        parser.add_argument('content', type=str)
        parser.add_argument('media_id', type=str)
        args = parser.parse_args()
        # 创建指定类型的消息
        if args['msg_type'] not in MSG_TYPE:
            return Resp.bad_request(errmsg='暂不支持的消息类型, {}'.format(args['msg_type']))
        title1 = args.title
        title2 = args.get('title')
        title3 = args['title']
        print(title1)
        print(title2)
        print(title3)
        if args['msg_type'] == 'text' and args['content']:
            message = Message(title=args['title'],
                              wx_app_id=args['wx_app_id'],
                              msg_type=args['msg_type'],
                              content=args['content'])
            message.save()
            """
            INSERT INTO silo.messages (created_at, updated_at, title, wx_app_id, deleted_at, msg_type, content, media_id) VALUES (%(created_at)s, %(updated_at)s, %(title)s, %(wx_app_id)s, %(deleted_at)s, %(msg_type)s, %(content)s, %(media_id)s)
            {'created_at': datetime.datetime(2021, 4, 21, 22, 26, 30, 926680), 'updated_at': datetime.datetime(2021, 4, 21, 22, 26, 30, 926730), 'title': 'create_message-3', 'wx_app_id': 0, 'deleted_at': None, 'msg_type': 'text', 'content': 'create_message_content-3', 'media_id': ''}
            """
            data = {
                'title': message.title,
                'msg_id': message.id,
                'wx_app_id': message.wx_app_id,
                'content': message.content,
                'media_id': message.media_id,
                'msg_type': message.msg_type,
                'update_at': str(message.updated_at),
                'created_at': str(message.created_at)
            }
            return Resp.ok(errmsg='Created', code=201, data=data)

        if (not args['wx_app_id']) and (args.msg_type != 'text'):
            return Resp.bad_request(errmsg='创建非文本消息, wx_app_id不能为零')
        
        if args.msg_type == 'news' and args.media_id:
            message = Message(title=args.title,
                              wx_app_id=args.wx_app_id,
                              msg_type=args.msg_type,
                              media_id=args.media_id)
            message.save()
            
            data = {
                'title': message.title,
                'msg_id': message.id,
                'wx_app_id': message.wx_app_id,
                'content': message.content,
                'msg_type': message.msg_type,
                'media_id': message.media_id,
                'update_at': str(message.updated_at),
                'created_at': str(message.created_at)
            }
            return Resp.ok(errmsg='Created', code=200, data=data)

        return Resp.ok(errmsg='您的media_id或者content为空')

